package com.dji.sdk.extensions.java.time.LocalDate;

import com.dji.sdk.extensions.java.time.LocalTime.LocalTimeExtension;
import manifold.ext.rt.api.Extension;

import java.time.*;
import java.time.zone.ZoneRules;
import java.util.Objects;

/**
 * @author 吴昊
 */
@Extension
public class LocalDateExtension {
    //-----------------------------------------------------------------------
    /**
     * Obtains an instance of {@code LocalDate} from an {@code Instant} and zone ID.
     * <p>
     * This creates a local date based on the specified instant.
     * First, the offset from UTC/Greenwich is obtained using the zone ID and instant,
     * which is simple as there is only one valid offset for each instant.
     * Then, the instant and offset are used to calculate the local date.
     *
     * @param instant  the instant to create the date from, not null
     * @param zone  the time-zone, which may be an offset, not null
     * @return the local date, not null
     * @throws DateTimeException if the result exceeds the supported range
     * @since 9
     */
    @Extension
    public static LocalDate ofInstant(Instant instant, ZoneId zone) {
        Objects.requireNonNull(instant, "instant");
        Objects.requireNonNull(zone, "zone");
        ZoneRules rules = zone.getRules();
        ZoneOffset offset = rules.getOffset(instant);
        long localSecond = instant.getEpochSecond() + offset.getTotalSeconds();
        long localEpochDay = Math.floorDiv(localSecond, LocalTimeExtension.SECONDS_PER_DAY);
        return LocalDate.ofEpochDay(localEpochDay);
    }
}
